<?php
	/**
	 * Login utility class.
	 * @author IMP
	 */
	
	class UserLogin {
		private $user = null,
				$session = false,
				$sessionVariable = array(),
				$validator;
		
		public function __construct(array &$session, UserLoginValidator $validator){
			$this->validator = $validator;
			$this->sessionVariable = &$session;
			
			if(!empty($session['ul_username']) && isset($session['ul_password'])){				
				$user = $this->validator->validate($this->sessionVariable['ul_username'], $this->sessionVariable['ul_password']);
				
				if($user !== null){
					$this->user = $user;
					$this->session = true;
				}else{
					unset($this->sessionVariable['ul_username'], $this->sessionVariable['ul_password']);
				}
			}
		}
		
		public function login(array &$data){
			if(!empty($data['ul_username']) && isset($data['ul_password'])){
				$user = $this->validator->validate($data['ul_username'], $data['ul_password']);
				
				if($user instanceof User){
					$this->user = $user;
					$this->sessionVariable['ul_username'] = $data['ul_username'];
					$this->sessionVariable['ul_password'] = $data['ul_password'];
					$this->session = true;
					
					return true;
				}
			}
		}
		
		public function isUserLoggedIn(){
			return $this->user != null;
		}
		
		public function getIdentification(){
			return $this->user;
		}
		
		public function logout(){
			$this->user = null;
			
			if($this->session){
				unset($this->sessionVariable['ul_username'], $this->sessionVariable['ul_password']);
			}
		}
	}
?>